package com.pompom.matchcrawler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class SkillMapBuilder {

	static HashMap<Integer, HashMap<Integer,Integer>> skillmap = new HashMap<Integer, HashMap<Integer,Integer>>();
	private static final int STATS_ID = 5002;
	public static void build(File f)
	{

		int cont=0;
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(f)); 
			String line;
			int skillIdInMap=0;
			while ((line = br.readLine()) != null) {
				String t[] = line.split(",");
				int heroId= Integer.parseInt(t[0]);
				int skillId= Integer.parseInt(t[1]);
				int skillMapped= Integer.parseInt(t[2]);
				
				HashMap<Integer, Integer> map = skillmap.get(heroId);
				if (map==null)
				{
					map = new HashMap<Integer, Integer>();
					skillmap.put(heroId, map);
					skillIdInMap=0;
				}
				skillIdInMap++;
				map.put(skillId, skillMapped);
			// 	System.out.println(""+heroId+","+skillId+","+skillMapped);
			}
		}catch (Exception e)
		{
			e.printStackTrace();
		}

	}
	
	public static int getMappedFromSkill(int skillid,int heroid, long matchid)
	{
		HashMap<Integer,Integer> skills = skillmap.get(heroid);
		if (skillid==0) return 0;
		if (skills == null)
		{
			System.out.println("ERROR null aqui1 ");
			return 1;
		}
		Integer s = skills.get(skillid);
		
		if (s==null)
			{
			System.out.println("WARNING mappedskill not available "+heroid+ " "+skillid+"  "+matchid);
			return 1;
			}
		else
			return s;
		
	}
	
	public static int getSkillFromMapped(int mappedId,int heroid)
	{
		
		if (mappedId==0)
			return -1;
		
	HashMap<Integer,Integer> skills = skillmap.get(heroid);
		
		if (skills == null)
		{
			System.out.println("ERROR null aqui2 ");
			return STATS_ID;
		}
		
		
		Set<Entry<Integer,Integer>> s = skills.entrySet();
		
		
		Iterator<Entry<Integer,Integer>>  i =     s.iterator();
		while (i.hasNext())
		{
			Entry<Integer,Integer> e = i.next();
			
			if (e.getValue() ==mappedId) return e.getKey();
			
		}
		System.out.println("WARNING map not found "+heroid+" "+mappedId);
		return STATS_ID;
	
		
	}
	
	public static long getBuildFromArray(int []build, int heroid, long matchid)
	{
		long ret=0;
		for (int i=0;i<build.length&& i<=18;i++)
		{
			long mult = (long)Math.pow(10, 18-i);
			ret+= mult*getMappedFromSkill(build[i],heroid,matchid);
			
		}
		
		return ret;
	}
	
	public static void testMap(long skillbuild)
	{
		
		String s = skillbuild+"";
		
		for (int i=0;i<s.length();i++)
			{
			int mapid = Integer.parseInt(s.charAt(i)+"");
			System.out.print(""+getSkillFromMapped(mapid, 8)+",");
			}
		System.out.println();
	}
}
